package com.itheima.ssm.service.impl;

import com.itheima.ssm.dao.IUserDao;
import com.itheima.ssm.domain.Role;
import com.itheima.ssm.domain.UserInfo;
import com.itheima.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        UserInfo userInfo=null;
        try {
           userInfo = userDao.findByName(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        List<Role> roles = userInfo.getRoles();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        User user=new User(userInfo.getUsername(),userInfo.getPassword(),list);

            return user;

    }

    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }
/*========================================================================================================================*/
 /*   @Override
    public void save(UserInfo users, String[] ids) {
        users.setPassword(bCryptPasswordEncoder.encode(users.getPassword()));
        userDao.save(users);
    }*/

    @Override
    public void save(UserInfo users, String[] roleIds) {
        users.setPassword(bCryptPasswordEncoder.encode(users.getPassword()));
        userDao.save(users);
        if (roleIds!=null) {
            for (String roleId : roleIds) {
                userDao.insertUserAndRole(users.getId(), roleId);
            }
        }

    }
/*=====================================================================================================================*/
    @Override
    public UserInfo findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public void addRoleAndUser(String uId, String[] rIds) {
        for (String rId : rIds) {
            userDao.insertUserAndRole(uId,rId);
        }
    }

}
